﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Antlers
{
	internal class DirectoryTree : TreeView
	{
		internal string ActivePath
		{
			get
			{
				if (SelectedNode != null)
				{
					return BuildPathFromNode(SelectedNode);
				}

				return String.Empty;
			}
		}

		internal void Init()
		{
			DriveInfo[] logicalDrives = DriveInfo.GetDrives();
			if (logicalDrives == null || logicalDrives.Length == 0)
			{
				throw new Exception("Could not find any logical drives!");
			}

			foreach (DriveInfo drive in logicalDrives)
			{
				if (drive.DriveType != DriveType.Fixed)
				{
					continue;
				}

				TreeNode node = new TreeNode(drive.Name);
				ExpandNode(node);
				Nodes.Add(node);
			}
		}

		internal void Handler_AfterExpand(object sender, TreeViewEventArgs args)
		{
			foreach (TreeNode node in args.Node.Nodes)
			{
				ExpandNode(node);
			}
		}

		private void ExpandNode(TreeNode node)
		{
			string path = BuildPathFromNode(node);
			DirectoryInfo root = new DirectoryInfo(path);
			foreach (DirectoryInfo subDir in root.GetDirectories())
			{
				if ((subDir.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0)
				{
					node.Nodes.Add(subDir.Name);
				}
			}
		}

		private string BuildPathFromNode(TreeNode node)
		{
			string path = node.Text;
			while (node.Parent != null)
			{
				node = node.Parent; 
				path = Path.Combine(node.Text, path);
			}

			return path;
		}
	}
}
